import * as RongIMLib from '@rongcloud/imlib-next'
import { xmtoast } from './public';
import { controlStore } from '@/pinia/modules/controller';
interface query {
  rong_token:string,
  gameRoomId:string
}
let onloadSet = false
export default (roomObj={} as query)=> {
  const useControlStore = controlStore()
  const {rong_token='', gameRoomId=0} = roomObj
  if(rong_token=='' || gameRoomId == 0) return console.error('rong error query')
  if(onloadSet) return console.error('error onloadSet:',onloadSet)
  RongIMLib.init({ appkey: import.meta.env.VITE_RONG });
  const Events = RongIMLib.Events
  RongIMLib.addEventListener(Events.CONNECTING, () => {
    onloadSet = true
    // console.log('正在链接服务器')
  })
  RongIMLib.addEventListener(Events.CONNECTED, () => {
    // console.log('onloadSet', onloadSet);
    // console.log('已经链接到服务器')
  })
  RongIMLib.addEventListener(Events.MESSAGES, (evt:any) => {
    useControlStore.getMessages(evt.messages)
  })
  RongIMLib.connect(rong_token).then(res => {
    if (res.code === RongIMLib.ErrorCode.SUCCESS) {
      RongIMLib.joinChatRoom(`${gameRoomId}`,{
        count:-1,
      }).then(({ code, data }) => {
        if (code === 0) {
          // console.log('获取会话列表成功', data);
        } else {
          xmtoast('room error code:' + code)
        }
      });
    } else {
      onloadSet = false
      xmtoast('链接失败, code:' + res.code)
    }
  })
}